//
//  DeviceSettingViewController.m
//  KEREN
//
//  Created by MW on 2023/3/14.
//

#import "DeviceSettingViewController.h"
#import "KRSettingCell.h"
#import "ChangeDeviceNameVC.h"
#import "DeviceShareVC.h"
#import "IntellectConfigVC.h"
#import "RunningInformationVC.h"
#import "DeviceDetalVC.h"
@interface DeviceSettingViewController ()<UITableViewDelegate,UITableViewDataSource,TZImagePickerControllerDelegate>{
    NSArray *_titleArr;
}
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) UIButton *closeBtn;
@property (nonatomic, copy) NSString *shareCountStr;
@end

@implementation DeviceSettingViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setNavViewWithRightTitle:@"" navColorIswhite:YES withTitle:@"车辆设置"];
    _shareCountStr = @"";
    //TODO 国际化
    _titleArr = @[@"车辆名称",@"用车分享",@"智能配置",@"运行信息",@"车辆信息"];
    [self tableView];
    if(self.deviceInfo.deviceConfig.bike_lock){
        [self setViewLayout];
    }

}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    if(_deviceInfo.is_manager)
    {
        [self getDevicesharelist];
    }else{
        [self.tableView reloadData];
    }
}

- (void)getDevicesharelist{
    WEAKSELF
    NSDictionary *parameters = @{@"ebike_id":@(_deviceInfo.Id),@"type":@(0)};
    [NetworkingTool POST:Device_share_list parameters:parameters isDeviceUrl:YES success:^(id  _Nonnull response, NSURLSessionDataTask * _Nonnull operation) {
        if([response[@"code"] intValue] == 0){
            if(response[@"data"][@"list"] && [response[@"data"][@"list"] isKindOfClass:[NSArray class]]){
                NSArray *arr = response[@"data"][@"list"];
                weakSelf.shareCountStr = [NSString stringWithFormat:@"%ld人",arr.count];
            }
        }
        [weakSelf.tableView reloadData];
    } failure:^(NSError * _Nonnull error, NSURLSessionDataTask * _Nonnull operation) {
        [weakSelf.tableView reloadData];
    }];
}


- (void)setViewLayout{
    //TODO 国际化
    _closeBtn = [UIButton setButtonWithTitle:@"锁定车辆" titleColor:Whire_Color titleFont:BFont(16) cornerRadius:25 backColor:Color_7ACC00];
    if([UserInfoManager sharedInstance].currentDeviceInfo.lock_status == 0){
        [_closeBtn setTitle:@"解除锁定" forState:UIControlStateNormal];
    }
    [self.view addSubview:_closeBtn];
    
    [_closeBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(24);
        make.right.offset(-24);
        make.height.offset(58);
        make.bottom.offset(-BottomSpance_height);
    }];
    [_closeBtn addTarget:self action:@selector(closeBtnClick) forControlEvents:UIControlEventTouchUpInside];
}

- (void)closeBtnClick{
    if(!_deviceInfo.is_manager){
        [[KRAlartManager shareInstance] showAlert:@"该功能仅对车主开放"];
        return;
    }
    CBPeripheralState p_state = [HABleManager checkBleConnectedState:self.deviceInfo.sn_code];
    if([_deviceInfo is4GDevice]){
        if(_deviceInfo.online_status == 0 && p_state != CBPeripheralStateConnected){
            [[KRAlartManager shareInstance] showAlert:@"车辆已离线"];
            return;
        }
    }else{
        if(p_state != CBPeripheralStateConnected){
            [[KRAlartManager shareInstance] showAlert:@"蓝牙未连上"];
            return;
        }
    }
    WEAKSELF
    if([UserInfoManager sharedInstance].currentDeviceInfo.lock_status == 1){
        [[KRAlartManager shareInstance] showTipsAlertWithTitle:@"确定锁定车辆吗？" decTitle:@"非静止状态锁定车辆存在安全风险" cancleBtnText:@"取消" andOkBtnText:@"确认" sucessBlock:^(BOOL isSucess){
            if(isSucess){
                [weakSelf lock];
            }
        }];
    }else{
        [self lock];
    }
}

-(void)lock{
    WEAKSELF
    [[KRAlartManager shareInstance] showLodingAlertView:@"努力加载中..."];
    [KeRenRequestTool deviceLockedStatusChange:self.deviceInfo status:YES success:^(BOOL netSuccess, BOOL status) {
        [[KRAlartManager shareInstance] hidenAlartView];
        if([UserInfoManager sharedInstance].currentDeviceInfo.lock_status == 0){
            [UserInfoManager sharedInstance].currentDeviceInfo.lock_status = 1;
            [weakSelf.closeBtn setTitle:@"锁定车辆" forState:UIControlStateNormal];
            [[KRAlartManager shareInstance] showAlert:@"解锁成功"];
        }else{
            [UserInfoManager sharedInstance].currentDeviceInfo.lock_status = 0;
            [weakSelf.closeBtn setTitle:@"解除锁定" forState:UIControlStateNormal];
            [[KRAlartManager shareInstance] showAlert:@"已锁定"];
        }
        [weakSelf.navigationController popViewControllerAnimated:YES];
    } failure:^(BOOL netFailure) {
        [[KRAlartManager shareInstance] hidenAlartView];
    }];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _titleArr.count;
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    KRSettingCell *cell = [tableView dequeueReusableCellWithIdentifier:@"KRSettingCell"];
    cell.nameLbl.text = _titleArr[indexPath.row];
    cell.rightIcon.hidden = NO;
    cell.photoIcon.hidden = YES;
    cell.decLbl.text = @"";
    if(_deviceInfo){
        if (indexPath.row == 0){
            cell.decLbl.text = _deviceInfo.name;
        }
    }
    if(indexPath.row == 1){
        cell.decLbl.text = _shareCountStr;
    }
    if(indexPath.row == _titleArr.count - 1){
        cell.lineView.hidden = YES;
    }else{
        cell.lineView.hidden = NO;
    }
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    if(!ISLOGIN){
        [[UserInfoManager sharedInstance] loginOut];
        return;
    }
    if(indexPath.row == 0){
        ChangeDeviceNameVC *vc = [[ChangeDeviceNameVC alloc] init];
        vc.deviceInfo = self.deviceInfo;
        [self.navigationController pushViewController:vc animated:YES];
    }else if (indexPath.row == 1){
        if(!_deviceInfo.is_manager){
            [[KRAlartManager shareInstance] showAlert:@"该功能仅对车主开放"];
        }else{
            DeviceShareVC *vc = [[DeviceShareVC alloc] init];
            vc.deviceInfo = self.deviceInfo;
            [self.navigationController pushViewController:vc animated:YES];
        }
    }else if (indexPath.row == 2){
        IntellectConfigVC *vc = [[IntellectConfigVC alloc] init];
        vc.ebike_id = (int)_deviceInfo.Id;
        vc.deviceInfo = _deviceInfo;
        [self.navigationController pushViewController:vc animated:YES];
    }else if (indexPath.row == 3){
        RunningInformationVC *vc = [[RunningInformationVC alloc] init];
        vc.deviceInfo = _deviceInfo;
        [self.navigationController pushViewController:vc animated:YES];
    }else if (indexPath.row == 4){
        DeviceDetalVC *vc = [[DeviceDetalVC alloc] init];
        vc.deviceInfo = _deviceInfo;
        [self.navigationController pushViewController:vc animated:YES];
    }
}

- (UITableView *)tableView{
    if(!_tableView){
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, NAVTOP_Height, DEVICE_WIDTH, DEVICE_HEIGHT - NAVTOP_Height)];
        _tableView.backgroundColor = Main_BackColor;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.rowHeight = 60;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [_tableView registerNib:[UINib nibWithNibName:@"KRSettingCell" bundle:nil] forCellReuseIdentifier:@"KRSettingCell"];
        [self.view addSubview:_tableView];
    }
    return _tableView;
}
- (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingPhotos:(NSArray<UIImage *> *)photos sourceAssets:(NSArray *)assets isSelectOriginalPhoto:(BOOL)isSelectOriginalPhoto{
    for (UIImage *img in photos) {
        NSData *imageData = UIImageJPEGRepresentation(img,1);;
        [[KRAlartManager shareInstance] showLodingAlertView:@"努力加载中..."];
        [[FlieUploadManager shareInstance] uploadImageToOss:imageData type:1 andCount:1 currentCount:0];
    }
}


@end
